package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.mapper.PermissionMapper;
import com.itheima.pojo.Permission;
import com.itheima.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

@Service(interfaceClass = PermissionService.class)
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public PageResult findPage(Integer currentPage, Integer pageSize, String queryString) {

        PageHelper.startPage(currentPage,pageSize);

        //条件查询分页数据
        List<Permission> permissions=  permissionMapper.findByCondition(queryString);

        //给PageInfo包装
        PageInfo<Permission> pageInfo = new PageInfo<>(permissions);

        PageResult pageResult = new PageResult(pageInfo.getTotal(), pageInfo.getList());

        return pageResult;
    }

    @Override
    public void add(Permission permission) {
        permissionMapper.add(permission);
    }

    @Override
    public Permission findById(Integer id) {
        Permission permission = permissionMapper.findById(id);
        return permission;
    }

    @Override
    public void deleteById(Integer id) {
        //查询当前检查项的id有没有被检查组引用
        Integer count = permissionMapper.findCountByCheckItemId(id);
        if (count>0){
            //如果大于0表示被某个检查组引用了，此时抛出异常，提示用户不能删除
            throw new RuntimeException(MessageConstant.PERMISSION_IS_QUOTED);
        }
        permissionMapper.deleteById(id);
    }

    @Override
    public void edit(Permission permission) {
        permissionMapper.edit(permission);
    }
}
